package org.sky.algorithm.tree;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BinaryTreeNode {

    private static final Logger log = LoggerFactory.getLogger(BinaryTreeNode.class);

    /**
     * 节点值
     */
    private int value;

    /**
     * 左节点
     */
    private BinaryTreeNode leftNode;

    /**
     * 右节点
     */
    private BinaryTreeNode rightNode;

    public BinaryTreeNode(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public BinaryTreeNode getLeftNode() {
        return leftNode;
    }

    public void setLeftNode(BinaryTreeNode leftNode) {
        this.leftNode = leftNode;
    }

    public BinaryTreeNode getRightNode() {
        return rightNode;
    }

    public void setRightNode(BinaryTreeNode rightNode) {
        this.rightNode = rightNode;
    }

    /**
     * 前序遍历
     */
    public void frontShow() {

        log.info("Node Value: {}", this.value);

        if (leftNode != null) {
            leftNode.frontShow();
        }

        if (rightNode != null) {
            rightNode.frontShow();
        }

    }

    /**
     * 中序遍历
     */
    public void middleShow() {

        if (leftNode != null) {
            leftNode.middleShow();
        }

        log.info("Node Value: {}", this.value);

        if (rightNode != null) {
            rightNode.middleShow();
        }
    }

    /**
     * 中序遍历
     */
    public void afterShow() {

        if (leftNode != null) {
            leftNode.afterShow();
        }

        if (rightNode != null) {
            rightNode.afterShow();
        }

        log.info("Node Value: {}", this.value);
    }

    public BinaryTreeNode frontSearch(int i) {

        BinaryTreeNode target = null;

        if (this.value == i) {
            return this;
        } else {

            if (leftNode != null) {
                target = leftNode.frontSearch(i);
            }

            if (target != null) {
                return target;
            }

            if (rightNode != null) {
                target = rightNode.frontSearch(i);
            }

        }

        return target;
    }
}
